﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CryptoChat.Models
{
	public class CryptoChatRepository
	{
		public static void AddUser(User user)
		{
			using (CryptoChatDataContext db = new CryptoChatDataContext())
			{
				db.Users.InsertOnSubmit(user);
				
				db.SubmitChanges();
			}
		}

		public static bool UserExists(string userName)
		{
			bool exists = false;

			using (CryptoChatDataContext db = new CryptoChatDataContext())
			{
				int count = db.Users.Count(u => u.UserName == userName);

				exists = count > 0;
			}

			return exists;
		}

		public static User GetUser(string userName)
		{
			User user = null;

			using (CryptoChatDataContext db = new CryptoChatDataContext())
			{
				user = db.Users.FirstOrDefault(u => u.UserName == userName);
			}

			return user;
		}

		public static User GetUser(int userId)
		{
			User user = null;

			using (CryptoChatDataContext db = new CryptoChatDataContext())
			{
				user = db.Users.FirstOrDefault(
					u => u.UserId == userId);
			}

			return user;
		}

		public static User[] GetOtherUsers(string currentUserName)
		{
			User[] otherUsers = null;

			using (CryptoChatDataContext db = new CryptoChatDataContext())
			{
				var users = db.Users.Where(u => u.UserName != currentUserName);

				otherUsers = users.ToArray();
			}

			return otherUsers;
		}
	}
}
